﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using DalGen.Entity;
using DalGen.Util;

namespace DalGen.ConnForm
{
	public partial class SQLForm : Form
	{
		public SQLForm()
		{
			InitializeComponent();
		}

		private void btnconn_Click(object sender, EventArgs e)
		{
			DataTable dtTables = new DataTable();
			try
			{
				dtTables = TestConn();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			finally
			{
			}

			comboBox1.DisplayMember = "Name";
			comboBox1.ValueMember = "Name";
			comboBox1.DataSource = dtTables;
		}

		private DataTable TestConn()
		{
			string uid = txtuid.Text;
			string pwd = txtpwd.Text;
			string server = txtserver.Text;
			string connStr = "Data Source=" + txtserver.Text + ";Password=" + txtpwd.Text + ";User ID=" + txtuid.Text + ";";

			DataTable dtTables = new DataTable();



			using (SqlConnection _conn = new SqlConnection(connStr))
			{
				if (_conn.State == ConnectionState.Closed)
					_conn.Open();

				
				SqlDataAdapter da = new SqlDataAdapter();


				da.SelectCommand = new SqlCommand("select Name from master.sys.databases order by Name", _conn);
				da.Fill(dtTables);


				if (_conn.State == ConnectionState.Open)
				{
					_conn.Close();
				}

			}


			return dtTables;

		}

		private void button2_Click(object sender, EventArgs e)
		{
            EProjectInfo entity = new EProjectInfo();
			entity.Server = txtserver.Text;
			entity.UID = txtuid.Text;
            entity.Pwd = txtpwd.Text;
			entity.DataBaseName = comboBox1.SelectedValue.ToString();
            entity.DataBaseType = "SQL Server";
			entity.DataBaseVer = "";
			entity.Guid = Guid.NewGuid().ToString();

			//查询版本号

            string connstr = "Data Source={0};DataBase={1};Password={2};User ID={3}";

            using (SqlConnection _conn = new SqlConnection(string.Format(connstr, entity.Server, "master", entity.Pwd, entity.UID)))
			{
				if (_conn.State == ConnectionState.Closed)
					_conn.Open();

				SqlCommand cmd = new SqlCommand("SELECT SERVERPROPERTY('ProductVersion') as VersionNumber", _conn);

                entity.DataBaseVer =cmd.ExecuteScalar().ToString();

				if (_conn.State == ConnectionState.Open)
				{
					_conn.Close();
				}

			}



			XmlHelper.AddDalInfo(entity);

			ManageForm form = new ManageForm();
			form.Show();
			this.Hide(); 


		}

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
            ManageForm form = new ManageForm();
            form.Show();

        }

	}
}
